1015B - Obtaining the String - CodeForces Solution


implementation *1200

Please click on ads to support us..

Python Code:

N = int(input())
s = input()
t = input()
if sorted(s) != sorted(t):
  print(-1)
else:
  ans = []
  
  for i in range(N):
    a = t[i]
    b = s.index(a)
    for j in range(b,0,-1):
      ans.append(str(j+i))
    s = s[:b] + s[b+1:]
  print(len(ans))
  print(" ".join(ans))

C++ Code:

#include <bits/stdc++.h>
using namespace std;
/*#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update> indexed_set;*/

// file I/O
/*ifstream ifs("input.txt");
ofstream ofs("output.txt");
#define cin ifs
#define cout ofs*/

/* ------------------------------------ */

template <typename T>
ostream& operator <<(ostream& output, const vector<T>& data) {
    for (const T& x : data)
        output << x <<" ";
    return output;
}
 
template<typename T>
istream& operator>>(istream& input,vector<T>& data) {
    for (auto& item : data)
        input >> item;
    return input;
}

/* ------------------------------------ */

typedef long long ll;
typedef long double ld;

#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()

#define SUM(v) accumulate(all(v), 0LL)
#define MIN(v) *min_element(all(v))
#define MAX(v) *max_element(all(v))

#define endl "\n"

const ll inf = 1e18;
const ll mod = 1e9 + 7;
const int MAX = 2e5+5;

/////////////////////////////////////////////

void solve() {
    ll n; cin>>n;
    string s,t; cin>>s>>t;
    vector<ll> ans;
    for(ll i=0; i<n; ++i) {
    	if(s[i] == t[i]) continue;
    	ll last = -1;
    	for(ll j=i+1; j<n; ++j) {
    		if(s[j] == t[i]) {
    			last = j;
    			break;
    		}
    	}
    	if(last == -1) {
    		cout<<-1;
    		return;
    	}
    	for(ll idx = last-1; idx>=i; --idx) {
    		swap(s[idx],s[idx+1]);
    		ans.push_back(idx+1);
    	}
    }
    cout<<ans.size()<<endl<<ans;
    return;
}

int main() {
    ios_base::sync_with_stdio(0);cin.tie(0);
    ll tc=1; 
    // cin>>tc;
    for(ll i=1; i<=tc; ++i) {
    	solve();
    }
    return 0;
}


Comments

Submit
0 Comments
More Questions

200B - Drinks
13A - Numbers
129A - Cookies
1367B - Even Array
136A - Presents
1450A - Avoid Trygub
327A - Flipping Game
411A - Password Check
1520C - Not Adjacent Matrix
1538B - Friends and Candies
580A - Kefa and First Steps
1038B - Non-Coprime Partition
43A - Football
50A - Domino piling
479A - Expression
1480A - Yet Another String Game
1216C - White Sheet
1648A - Weird Sum
427A - Police Recruits
535A - Tavas and Nafas
581A - Vasya the Hipster
1537B - Bad Boy
1406B - Maximum Product
507B - Amr and Pins
379A - New Year Candles
1154A - Restoring Three Numbers
750A - New Year and Hurry
705A - Hulk
492B - Vanya and Lanterns
1374C - Move Brackets